package com.dms.modules.order.controller;

import com.dms.common.api.ApiResponse;
import com.dms.common.exception.BusinessException;
import com.dms.modules.order.entity.Coupon;
import com.dms.modules.order.entity.UserCoupon;
import com.dms.modules.order.service.CouponService;
import com.dms.modules.order.service.UserCouponService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.List;

/**
 * 优惠券控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/coupons")
@Api(tags = "优惠券管理")
@Validated
public class CouponController {

    @Autowired
    private CouponService couponService;

    @Autowired
    private UserCouponService userCouponService;

    @ApiOperation("获取所有可用优惠券")
    @GetMapping("/list")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public ApiResponse<List<Coupon>> list() {
        try {
            List<Coupon> coupons = couponService.getAvailableCoupons();
            return ApiResponse.success(coupons);
        } catch (BusinessException e) {
            log.warn("获取优惠券列表失败: {}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("获取优惠券列表失败", e);
            return ApiResponse.error("获取优惠券列表失败");
        }
    }

    @ApiOperation("获取商家可用优惠券")
    @GetMapping("/merchant/{merchantId}")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN', 'MERCHANT')")
    public ApiResponse<List<Coupon>> getMerchantCoupons(
            @ApiParam("商家ID") @PathVariable @NotNull(message = "商家ID不能为空") Long merchantId) {
        try {
            List<Coupon> coupons = couponService.getMerchantCoupons(merchantId);
            return ApiResponse.success(coupons);
        } catch (BusinessException e) {
            log.warn("获取商家优惠券失败: {}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("获取商家优惠券失败", e);
            return ApiResponse.error("获取商家优惠券失败");
        }
    }

    @ApiOperation("获取分类可用优惠券")
    @GetMapping("/category/{categoryId}")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public ApiResponse<List<Coupon>> getCategoryCoupons(
            @ApiParam("分类ID") @PathVariable @NotNull(message = "分类ID不能为空") Long categoryId) {
        try {
            List<Coupon> coupons = couponService.getCategoryCoupons(categoryId);
            return ApiResponse.success(coupons);
        } catch (BusinessException e) {
            log.warn("获取分类优惠券失败: {}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("获取分类优惠券失败", e);
            return ApiResponse.error("获取分类优惠券失败");
        }
    }

    @ApiOperation("获取用户可用优惠券")
    @GetMapping("/user/{userId}")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')")
    public ApiResponse<List<UserCoupon>> getUserCoupons(
            @ApiParam("用户ID") @PathVariable @NotNull(message = "用户ID不能为空") Long userId,
            @ApiParam("商家ID") @RequestParam(required = false) Long merchantId,
            @ApiParam("订单金额") @RequestParam(required = false) BigDecimal totalAmount) {
        try {
            List<UserCoupon> userCoupons = userCouponService.getAvailableCoupons(userId, merchantId, totalAmount);
            return ApiResponse.success(userCoupons);
        } catch (BusinessException e) {
            log.warn("获取用户优惠券失败: {}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("获取用户优惠券失败", e);
            return ApiResponse.error("获取用户优惠券失败");
        }
    }

    @ApiOperation("领取优惠券")
    @PostMapping("/receive")
    @PreAuthorize("hasRole('USER')")
    public ApiResponse<Boolean> receiveCoupon(
            @ApiParam("用户ID") @RequestParam @NotNull(message = "用户ID不能为空") Long userId,
            @ApiParam("优惠券ID") @RequestParam @NotNull(message = "优惠券ID不能为空") Long couponId) {
        try {
            boolean result = userCouponService.receiveCoupon(userId, couponId);
            if (result) {
                return ApiResponse.success(true);
            } else {
                return ApiResponse.error("领取优惠券失败");
            }
        } catch (BusinessException e) {
            log.warn("领取优惠券失败: {}", e.getMessage());
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error("领取优惠券失败", e);
            return ApiResponse.error("领取优惠券失败");
        }
    }
} 